package com.haixiaoke.saas.messageCenter.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.haixiaoke.saas.common.constant.ContractConstants;
import com.haixiaoke.saas.common.constant.MessageConstants;
import com.haixiaoke.saas.common.constant.WorkOrderConstants;
import com.haixiaoke.saas.common.enums.OrderStateEnum;
import com.haixiaoke.saas.common.enums.PushConditionEnum;
import com.haixiaoke.saas.common.exception.ServiceException;
import com.haixiaoke.saas.messageCenter.domain.OrdinaryMessage;
import com.haixiaoke.saas.messageCenter.domain.OrdinaryMessageUser;
import com.haixiaoke.saas.messageCenter.mapper.OrdinaryMessageUserMapper;
import com.haixiaoke.saas.messageCenter.service.IOrdinaryMessageUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 普通消息推送与用户关联数据Service业务层处理
 *
 * @author panda
 * @date 2024-11-08
 */
@Service
public class OrdinaryMessageUserServiceImpl implements IOrdinaryMessageUserService {
    @Autowired
    private OrdinaryMessageUserMapper ordinaryMessageUserMapper;

    /**
     * 查询普通消息推送与用户关联数据
     *
     * @param ordinaryMessageId 普通消息推送与用户关联数据主键
     * @return 普通消息推送与用户关联数据
     */
    @Override
    public List<OrdinaryMessageUser> selectOrdinaryMessageUserByOrdinaryMessageId(Long ordinaryMessageId) {
        return ordinaryMessageUserMapper.selectOrdinaryMessageUserByOrdinaryMessageId(ordinaryMessageId);
    }

    /**
     * 查询普通消息推送与用户关联数据列表
     *
     * @param ordinaryMessageUser 普通消息推送与用户关联数据
     * @return 普通消息推送与用户关联数据
     */
    @Override
    public List<OrdinaryMessageUser> selectOrdinaryMessageUserList(OrdinaryMessageUser ordinaryMessageUser) {
        return ordinaryMessageUserMapper.selectOrdinaryMessageUserList(ordinaryMessageUser);
    }

    /**
     * 新增普通消息推送与用户关联数据
     *
     * @param ordinaryMessageUser 普通消息推送与用户关联数据
     * @return 结果
     */
    @Override
    public int insertOrdinaryMessageUser(OrdinaryMessageUser ordinaryMessageUser) {
        return ordinaryMessageUserMapper.insertOrdinaryMessageUser(ordinaryMessageUser);
    }

    /**
     * 修改普通消息推送与用户关联数据
     *
     * @param ordinaryMessageUser 普通消息推送与用户关联数据
     * @return 结果
     */
    @Override
    public int updateOrdinaryMessageUser(OrdinaryMessageUser ordinaryMessageUser) {
        return ordinaryMessageUserMapper.updateOrdinaryMessageUser(ordinaryMessageUser);
    }

    /**
     * 批量删除普通消息推送与用户关联数据
     *
     * @param ordinaryMessageIds 需要删除的普通消息推送与用户关联数据主键
     * @return 结果
     */
    @Override
    public int deleteOrdinaryMessageUserByOrdinaryMessageIds(Long[] ordinaryMessageIds) {
        return ordinaryMessageUserMapper.deleteOrdinaryMessageUserByOrdinaryMessageIds(ordinaryMessageIds);
    }

    /**
     * 删除普通消息推送与用户关联数据信息
     *
     * @param ordinaryMessageId 普通消息推送与用户关联数据主键
     * @return 结果
     */
    @Override
    public int deleteOrdinaryMessageUserByOrdinaryMessageId(Long ordinaryMessageId) {
        return ordinaryMessageUserMapper.deleteOrdinaryMessageUserByOrdinaryMessageId(ordinaryMessageId);
    }

    @Override
    public int insertBatchOrdinaryMessageUser(List<OrdinaryMessageUser> ordinaryMessageUserList) {
        return ordinaryMessageUserMapper.insertBatchOrdinaryMessageUser(ordinaryMessageUserList);
    }

    @Override
    public List<OrdinaryMessageUser> getUserByPushCondition(OrdinaryMessage ordinaryMessage) {
        if (ordinaryMessage.getOrdinaryMessageId() == null) {
            throw new ServiceException("消息推送ID不能为空");
        }
        if (!StrUtil.equals(MessageConstants.TRIGGERING_BEHAVIOR_CONDITION_PUSH, ordinaryMessage.getTriggeringBehavior())) {
            throw new ServiceException("触发行为异常");
        }
        if (StrUtil.isBlank(ordinaryMessage.getPushConditionCode())) {
            throw new ServiceException("推送条件编码不能为空");
        }
        PushConditionEnum enumByCode = PushConditionEnum.getEnumByCode(ordinaryMessage.getPushConditionCode());
        if (enumByCode == null) {
            throw new ServiceException("推送条件编码异常");
        }
        List<OrdinaryMessageUser> ordinaryMessageUserList = new ArrayList<>();
        if (StrUtil.equals(MessageConstants.PUSH_CHANNEL_RENTER_APPLET, ordinaryMessage.getPushChannel())) {
            //C端用户
            switch (enumByCode) {
                case CONDITION_TYPE_PENDING_CON:
                    //外部消息: 101.工单接单通知
                    ordinaryMessageUserList = this.selectOrdinaryMessageUserListByWorkOrder(WorkOrderConstants.WORK_ORDER_STATE_RECEIVED,
                            false, false);
                    break;
                case CONDITION_TYPE_CANCEL_CON:
                    //外部消息: 102.工单取消通知
                    ordinaryMessageUserList = this.selectOrdinaryMessageUserListByWorkOrder(WorkOrderConstants.WORK_ORDER_STATE_CANCELED,
                            false, false);
                    break;
                case CONDITION_TYPE_TIMEOUT_CON:
                    //外部消息: 103.工单超时处理通知
                    ordinaryMessageUserList = this.selectOrdinaryMessageUserListByWorkOrder(null, false, true);
                    break;
                case CONDITION_TYPE_RESERVE_CON:
                    //外部消息: 104.预订成功通知
                    ordinaryMessageUserList = this.selectOrdinaryMessageUserListByOrder(OrderStateEnum.ORDER_STATE_STAY_CHECK_IN.getValue(), false);
                    break;
                case CONDITION_TYPE_UNPAID_CON:
                    //外部消息: 105.订单待支付通知
                    ordinaryMessageUserList = this.selectOrdinaryMessageUserListByOrder(OrderStateEnum.ORDER_STATE_OBLIGATION.getValue(), false);
                    break;
                case CONDITION_TYPE_TENANT_CONTRACT_NOTARIZE_CON:
                    //外部消息: 106.租客合同待确认通知
                    ordinaryMessageUserList = this.selectOrdinaryMessageUserListByLesseeContract(ContractConstants.LESSEE_CONTRACT_STATUS_UNCONFIRMED, false);
                    break;
                case CONDITION_TYPE_TENANT_CONTRACT_EXPIRE_CON:
                    //外部消息: 107.租客合同到期通知
                    ordinaryMessageUserList = this.selectOrdinaryMessageUserListByLesseeContract(ContractConstants.LESSEE_CONTRACT_STATUS_OVERDUE, false);
                    break;
                default:
                    break;
            }
        } else {
            //B端用户
            switch (enumByCode) {
                case CONDITION_TYPE_PENDING:
                    //内部消息: 1.工单待接单通知
                    ordinaryMessageUserList = this.selectOrdinaryMessageUserListByWorkOrder(WorkOrderConstants.WORK_ORDER_STATE_WAIT_DISPATCH,
                            true, false);
                    break;
                case CONDITION_TYPE_AUDIT:
                    //外部消息: 2.工单审核通知
                    ordinaryMessageUserList = this.selectOrdinaryMessageUserListByWorkOrder(WorkOrderConstants.WORK_ORDER_STATE_WAIT_AUDIT,
                            true, false);
                    break;
                case CONDITION_TYPE_TIMEOUT:
                    //外部消息: 3.工单超时处理通知
                    ordinaryMessageUserList = this.selectOrdinaryMessageUserListByWorkOrder(null, true, true);
                    break;
                case CONDITION_TYPE_RESERVE:
                    //外部消息: 4.预订成功通知（日租）
                    ordinaryMessageUserList = this.selectOrdinaryMessageUserListByOrder(OrderStateEnum.ORDER_STATE_STAY_CHECK_IN.getValue(), true);
                    break;
                case CONDITION_TYPE_LETTING_OUT:
                    //外部消息: 5.退订审核通知
                    ordinaryMessageUserList = this.selectOrdinaryMessageUserListByOrder(OrderStateEnum.ORDER_STATE_REFUND_RENT_AUDIT.getValue(), true);
                    break;
                case CONDITION_TYPE_CHANGE:
                    //外部消息: 6.换房申请通知
                    ordinaryMessageUserList = this.selectOrdinaryMessageUserListByOrder(OrderStateEnum.ORDER_STATE_CHANGE_ROOM_AUDIT.getValue(), true);
                    break;
                case CONDITION_TYPE_RELET:
                    //外部消息: 7.续租申请通知
                    ordinaryMessageUserList = this.selectOrdinaryMessageUserListByOrder(OrderStateEnum.ORDER_STATE_RELET_AUDIT.getValue(), true);
                    break;
                case CONDITION_TYPE_SUBLET:
                    //外部消息: 8.转租申请通知
                    ordinaryMessageUserList = this.selectOrdinaryMessageUserListByOrder(OrderStateEnum.ORDER_STATE_SUBLET_AUDIT.getValue(), true);
                    break;
                case CONDITION_TYPE_TENANT_CONTRACT_NOTARIZE:
                    //外部消息: 9.租客合同待确认通知
                    ordinaryMessageUserList = this.selectOrdinaryMessageUserListByLesseeContract(ContractConstants.LESSEE_CONTRACT_STATUS_UNCONFIRMED, true);
                    break;
                case CONDITION_TYPE_TENANT_CONTRACT_EXPIRE:
                    //外部消息: 10.租客合同到期通知
                    ordinaryMessageUserList = this.selectOrdinaryMessageUserListByLesseeContract(ContractConstants.LESSEE_CONTRACT_STATUS_OVERDUE, true);
                    break;
                default:
                    break;
            }

        }
        if (CollectionUtil.isNotEmpty(ordinaryMessageUserList)) {
            if (CollectionUtil.isNotEmpty(ordinaryMessage.getOrdinaryMessageUserList())) {
                //获取新获取的用户数据与已存在的用户数据进行去重
                ordinaryMessageUserList.removeAll(ordinaryMessage.getOrdinaryMessageUserList());
                ordinaryMessageUserList = ordinaryMessageUserList.stream().filter(
                                a -> ordinaryMessage.getOrdinaryMessageUserList().stream()
                                        .noneMatch(messageUser -> a.getUserId().equals(messageUser.getUserId())
                                                && StrUtil.equals(a.getBusinessId(), messageUser.getBusinessId())
                                                && StrUtil.equals(a.getBusinessType(), messageUser.getBusinessType())))
                        .collect(Collectors.toList());
            }
            ordinaryMessageUserList.forEach(a -> a.setOrdinaryMessageId(ordinaryMessage.getOrdinaryMessageId()));
        }
        return ordinaryMessageUserList;
    }

    @Override
    public List<OrdinaryMessageUser> selectOrdinaryMessageUserListByWorkOrder(String workOrderState, boolean userType, boolean timeoutFlag) {
        return ordinaryMessageUserMapper.selectOrdinaryMessageUserListByWorkOrder(workOrderState, userType, timeoutFlag);
    }

    @Override
    public List<OrdinaryMessageUser> selectOrdinaryMessageUserListByOrder(String orderState, boolean userType) {
        return ordinaryMessageUserMapper.selectOrdinaryMessageUserListByOrder(orderState, userType);
    }

    @Override
    public List<OrdinaryMessageUser> selectOrdinaryMessageUserListByLesseeContract(String lesseeContractStatus, boolean userType) {
        List<OrdinaryMessageUser> ordinaryMessageUserList;
        if (userType) {
            //B端房管家用户,平台与租客签约的租客合同
            ordinaryMessageUserList = ordinaryMessageUserMapper.selectListByBusUserLesseeContract(lesseeContractStatus);
        } else {
            //C端用户-租客,平台与租客签约的租客合同
            //C端用户-业主、租客,业主与租客签约的租客合同
            ordinaryMessageUserList = ordinaryMessageUserMapper.selectListByConUserLesseeContract(lesseeContractStatus);
        }
        return ordinaryMessageUserList;
    }
}
